from django.http import Http404
from django.urls import reverse
from django import forms

from django.shortcuts import render, redirect
from django.core.exceptions import ValidationError

from wepapi.models import Admin
from wepapi.utils.bootstrap import BootStrapModelForm
from wepapi.utils.Pagination import Pagination
from wepapi.utils.encrypt import md5


def admin_list(request):
    """管理员列表"""

    # info_dict = request.session['info']
    # print(info_dict['id'])
    # print(info_dict['username'])


    # 检查用户是否登录，已登录继续往下走，未登录，跳转到登录页面
    # 用户发来的请求，获取cookie 随机字符串，拿着随机字符串看看cookie中有没有
    # request.session.get["info]
    #
    # info = request.session.get('info')
    # if info is None:
    #     return  redirect(reverse('account_login'))

    # 搜索
    data_dict = {}
    search_data = request.GET.get('q', '')
    if search_data:
        data_dict['username__contains'] = search_data

    queryset = Admin.objects.filter(**data_dict)
    # 分页
    page_object = Pagination(request, queryset)
    context = {
        "search_data": search_data,
        "queryset": page_object.page_queryset,  # 分完页的数据
        "page_string": page_object.html(),  # 生成页码
    }
    return render(request, "admin_list.html", context)


class AdminModelForm(BootStrapModelForm):
    confirm_password = forms.CharField(
        label="确认密码",
        widget=forms.PasswordInput(render_value=True)
    )

    class Meta:
        model = Admin
        fields = ['username', 'password', 'confirm_password']
        widgets = {
            'password': forms.PasswordInput(render_value=True)
        }

    def clean_password(self):
        password = self.cleaned_data.get('password')
        return md5(password)

    def clean_confirm_password(self):
        username = self.cleaned_data.get('username')
        password = self.cleaned_data.get('password')
        confirm = md5(self.cleaned_data.get('confirm_password'))
        if confirm != password:
            raise ValidationError('密码不一致')
        # if Admin.objects.filter(username=username).exists():
        #     raise forms.ValidationError("该账号已存在。")
        return confirm


class AdminEditModelForm(BootStrapModelForm):
    class Meta:
        model = Admin
        fields = ['username']


class AdminResetModelForm(BootStrapModelForm):
    confirm_password = forms.CharField(
        label="确认密码",
        widget=forms.PasswordInput(render_value=True)
    )

    class Meta:
        model = Admin
        fields = ['password', 'confirm_password']
        widgets = {
            'password': forms.PasswordInput(render_value=True)
        }

    def clean_password(self):
        password = self.cleaned_data.get('password')
        md5_pwd = md5(password)
        # 去数据库校验当前密码核心输入的密码是否一致
        exists = Admin.objects.filter(id=self.instance.pk, password=md5_pwd).exists()
        if exists:
            raise ValidationError("密码不能与前密码一致")
        return md5_pwd

    def clean_confirm_password(self):
        password = self.cleaned_data.get('password')
        confirm = md5(self.cleaned_data.get('confirm_password'))
        if confirm != password:
            raise ValidationError('密码不一致')
        return confirm


def admin_add(request):
    """添加管理"""
    if request.method == 'GET':
        form = AdminModelForm()
        return render(request, 'change.html', {'uform': form, 'title': '新建管理员'})

    form = AdminModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        return redirect(reverse("admin_list"))

    return render(request, 'change.html', {'uform': form, 'title': '新建管理员'})

    # if request.method == 'POST':
    #     return render(request, 'admin_add.html')
    #     user_name = request.POST.get('username')
    #     if not user_name:
    #         return HttpResponse("角色名称不能为空")
    #     Admin.objects.create(username=user_name)
    #     return redirect(reverse("admin_add"))


def admin_edit(request, id):
    """修改用户名"""
    row_object = Admin.objects.filter(id=id).first()
    if not row_object:
        # raise redirect(reverse('admin_list'))
        return render(request, 'error.html', {'msg': '数据不存在'})

    if request.method == 'GET':
        uform = AdminEditModelForm(instance=row_object)
        return render(request, 'change.html', {'uform': uform, 'title': '编辑管理员'})
    form = AdminEditModelForm(request.POST, instance=row_object)
    if form.is_valid():
        form.save()
        return redirect(reverse("admin_list"))
    return render(request, 'change.html', {'uform': form, 'title': '编辑管理员'})


# if request.method == 'GET':
#         row_object = Admin.objects.filter(id=id).first()
#         return render(request, 'admin_edit.html', {'row_object': row_object})
#
#     Admin.objects.filter(id=id).update(username=request.POST.get('username'))
#     return redirect(reverse("admin_list"))


def admin_del(request, id):
    if request.method == 'GET':
        Admin.objects.filter(id=id).delete()
        return redirect(reverse("admin_list"))


def admin_reset(request, id):
    """重置密码"""
    row_object = Admin.objects.filter(id=id).first()
    if not row_object:
        # raise redirect(reverse('admin_list'))
        return render(request, 'error.html', {'msg': '数据不存在'})

    title = '重置密码 - {}'.format(row_object.username)
    if request.method == 'GET':
        uform = AdminResetModelForm()
        return render(request, 'change.html', {'uform': uform, 'title': title})

    form = AdminResetModelForm(request.POST, instance=row_object)
    if form.is_valid():
        form.save()
        return redirect(reverse("admin_list"))
    return render(request, 'change.html', {'uform': form, 'title': title})
